<?php defined('SYSPATH') or die('No direct script access.');
/**
 * $Id: topic.php 50 2008-07-27 09:06:29Z geertdd $
 *
 * @package    PianissiBoard
 * @author     Geert De Deckere
 */
class Topic_Controller extends Pianissibase_Controller {

	/**
	 * URL: /pianissiboard/topic/{id}/{slug}[/page/{number}]
	 *                                      [/post/{id}]
	 * View a single topic.
	 */
	public function index()
	{
		// Non-existing topic id
		if (($topic = $this->topic->get_by_id($this->uri->segment(3))) === FALSE)
			Event::run('system.404');

		// Validate topic slug
		if ($this->uri->segment(4) !== $topic->slug)
			url::redirect('pianissiboard/topic/'.$topic->id.'/'.$topic->slug.'/'.implode('/', $this->uri->segment_array(4)), 301);

		// Redirect to specific post
		if ($this->uri->segment(5) === 'post' AND $url = $this->post->url($this->uri->segment(6), $topic->id))
			url::redirect($url);

		// Setup template
		$this->template->pagetitle = $topic->title;
		$this->template->content = new View('pianissiboard/topic');
		$this->template->content->topic = $topic;

		// Pagination setup
		$pagination = new Pagination(array
		(
			'group'       => 'posts',
			'base_url'    => 'pianissiboard/topic/'.$topic->id.'/'.$topic->slug.'/page/{page}',
			'uri_segment' => 6,
			'total_items' => $this->post->count($topic->id),
		));

		// Load topics and pagination into template
		$this->template->content->pagination = $pagination;
		$this->template->content->posts = $this->post->get(array
		(
			'topic_id' => $topic->id,
			'limit'    => $pagination->items_per_page,
			'offset'   => $pagination->sql_offset,
		));

		// Initialize post form (at the bottom of each page)
		$this->template->content->new_topic = FALSE;
		$this->template->content->preview = FALSE;
		$this->template->content->postform = (object) array
		(
			'author'   => (string) cookie::get('author'),
			'email'    => (string) cookie::get('email'),
			'website'  => (cookie::get('author') ? (string) cookie::get('website') : 'http://'),
			'post'     => '',
			'remember' => (bool) cookie::get('author'),
			'captcha'  => '',
		);
	}

}